package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;
import com.zzyl.constant.CacheConstants;
import com.zzyl.dto.DeviceDto;
import com.zzyl.entity.Device;
import com.zzyl.enums.BasicEnum;
import com.zzyl.enums.DeviceLocationTypeEnum;
import com.zzyl.enums.DevicePhysicalLocationTypeEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.DeviceMapper;
import com.zzyl.properties.AliIoTConfigProperties;
import com.zzyl.service.DeviceService;
import com.zzyl.vo.ProductVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description DeviceServiceImpl
 * @Author jiangweicong
 * @Date 2025-05-19  18:18
 */
@Service
public class DeviceServiceImpl implements DeviceService {

    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;

    @Autowired
    private Client client;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private DeviceMapper deviceMapper;

    /**
     * 同步数据
     */
    @Override
    public void syncProductList() {
        // 请求参数
        QueryProductListRequest queryProductListRequest = new QueryProductListRequest();
        queryProductListRequest.setPageSize(200);
        queryProductListRequest.setCurrentPage(1);
        queryProductListRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        // 调用第三方查询产品列表
        QueryProductListResponse response = null;
        try {
            response = client.queryProductList(queryProductListRequest);
        } catch (Exception e) {
            throw new BaseException(BasicEnum.IOT_LIST_PRODUCT_ERROR);
        }
        // 接口是否调通
        if (!response.getBody().getSuccess()) {
            throw new RuntimeException(response.getBody().getErrorMessage());
        }

        // 获取数据，存储到redis
        List<ProductVo> productVoList = response.getBody().getData().getList().getProductInfo()
                .stream().map(p -> BeanUtil.toBean(p, ProductVo.class)).collect(Collectors.toList());
        // 存储到redis
        redisTemplate.opsForValue().set(CacheConstants.ALL_PRODUCT_KEY, JSONUtil.toJsonStr(productVoList));
    }

    @Override
    @ApiOperation(value = "查询所有产品")
    public List<ProductVo> allProduct() {
        // 从redis查询所有的产品数据
        String productListJsonStr = redisTemplate.opsForValue().get(CacheConstants.ALL_PRODUCT_KEY);
        if (ObjectUtil.isEmpty(productListJsonStr)) {
            return Collections.emptyList();
        }
        return JSONUtil.toList(productListJsonStr, ProductVo.class);
    }

    @Override
    @ApiOperation(value = "注册设备")
    public void RegisterDevice(DeviceDto deviceDto) {
        // 判断数据库里有没有这个设备
        String deviceName = deviceDto.getDeviceName();
        Long count = deviceMapper.countByDeviceName(deviceName);
        if (count > 0) {
            throw new BaseException(BasicEnum.DEVICE_NAME_EXIST);
        }
        // 没有的话新增，先调用物联网平台去注册
        RegisterDeviceRequest registerDeviceRequest = new RegisterDeviceRequest();
        registerDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        RegisterDeviceResponse response = null;
        try {
            response = client.registerDevice(registerDeviceRequest);
        }catch(Exception e){
            throw new BaseException(BasicEnum.IOT_REGISTER_DEVICE_ERROR);
        }
        //接口是否调通
        if(!response.getBody().getSuccess()){
            throw new RuntimeException(response.getBody().getErrorMessage());
        }
        //根据productKey调阿里云查询产品信息，获取productName
        QueryProductRequest queryProductRequest = new QueryProductRequest();
        queryProductRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        queryProductRequest.setProductKey(deviceDto.getProductKey());
        QueryProductResponse queryProductResponse = null;
        try{
            queryProductResponse = client.queryProduct(queryProductRequest);
        }catch(Exception e){
            throw new BaseException(BasicEnum.IOT_QUERY_PRODUCT_ERROR);
        }
        // 接口是否调通
        if(!queryProductResponse.getBody().getSuccess()){
            throw new RuntimeException(response.getBody().getErrorMessage());
        }

        //保存设备
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setIotId(response.getBody().getData().getIotId());
        device.setProductName(queryProductResponse.getBody().getData().getProductName());
        //如果设备绑定的位置是随身设备，则把物理绑定位置设置为-1
        if(device.getLocationType().equals(DeviceLocationTypeEnum.PORTABLE_DEVICE.getOrdinal())){
            device.setPhysicalLocationType(DevicePhysicalLocationTypeEnum.ELDER.getOrdinal());
        }
        deviceMapper.insertSelective(device);
    }
}
